// index.js
//获取应用实例
var app = getApp();

var util = require('../../utils/util.js');

var fileData = require('../../utils/userSig.js')
/**
 * dialog对话框
 */
var dialog = require('../../utils/dialog/dialog.js');
var imutil = require("../../utils/imutil.js");
//获取解密电话号码的js模块
var WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
Page({
  data: {
    username: '',
    password: '',
    loginBtnShow: true,
    telephone: '',
    btnValue: "获取电话",
    phoneNumber:'', //手机号
    phCode:'', // 验证码
    information:false,

    getPhoneNumbers:false,
    getUser:false,
    encryptedData1:'',
    iv1:'',
    navH:0
  },

  // get the user name
  usernameInput: function(e) {
    this.setData({
      username: e.detail.value
    });
  },
  //end get the user name

  // get the password
  passwordInput: function(e) {
    this.setData({
      password: e.detail.value
    });
  },

  
  //end get the password

  getPhoneNumberAndLogin:function(){

  },

  onLoad: function() {

    let that=this
    this.setData({
      navH: app.globalData.navHeight
    })


    // wx.getStorageSync('token')},

    wx.request({
      url: util.api+"/iim/im/viewUser",
      data: {id:wx.getStorageSync('userId')},
      success: function(res) {
        var tmpsig = res.data;

        if(tmpsig.success){
          console.log(tmpsig.body.data.hasOwnProperty('mobile'))
          if(!tmpsig.body.data.hasOwnProperty('mobile')){
          }else{
            wx.setStorageSync('isRegistered', tmpsig.body.data.mobile);
          }
        }
      },
      fail: function(resp) {
        console.log("getUserSigByTelephone failed,the response is %o", resp)
        return false;
      }
    })


  },


  
  onTabItemTap(item) {
    console.log("进入logo")
    let that=this

    
    var token1 = wx.getStorageSync('token')

    if (token1) {

      
      setTimeout(() => {

        var isRegistered = wx.getStorageSync('isRegistered');

        if (isRegistered) {
          this.setData({
            telephone:isRegistered,
            getPhoneNumbers: false
          });
        }else{
          that.setData({
            getPhoneNumbers: true
          })
        }

      }, 500);


    

    }else{
      that.setData({
        getPhoneNumbers: false,
        getUser: true
      })
    }





   


    // wx.request({
    //   url: util.api+"/iim/im/viewUser",
    //   data: {id:wx.getStorageSync('userId')},
    //   success: function(res) {
    //     var tmpsig = res.data;
    //     if(tmpsig.success){
    //       console.log('mobile========'+tmpsig.body.data.hasOwnProperty('mobile'))
    //       if(!tmpsig.body.data.hasOwnProperty('mobile') || tmpsig.body.data.mobile==''){
    //         that.setData({
    //           getPhoneNumbers: true
    //         })
    //       }else{
    //       var isRegistered = wx.getStorageSync('isRegistered');
    //       if (isRegistered) {
    //         this.setData({
    //           telephone:isRegistered
    //         });
    //     }
    //     that.setData({
    //         getPhoneNumbers: false
    //     })
    //       }
    //     }
    //   },
    //   fail: function(resp) {
    //     console.log("getUserSigByTelephone failed,the response is %o", resp)
    //     return false;
    //   }
    // })

    // wx.showToast({
    //   title: 'tab点击',
    // })
  },




  
  getPhoneNumber: function(e) {  // 获取手机号
    console.log(e,1111)
    let that=this
    wx.checkSession({
      success:function(res){
        console.log(res,'登录未过期')

        if (e.detail.errMsg==='getPhoneNumber:ok') {

          // that.setData({
          //   encryptedData1:e.detail.encryptedData,
          //   iv1: e.detail.iv,
          //   getPhoneNumbers:false
          // })

          let token1=wx.getStorageSync('token')
          wx.request({
            // url: "https://www.cdlpkj.cn/school/a/iim/im/onLogin",
            url: util.api+"/iim/im/decryptPhone",
            data: {
              token:token1,
              encryptedData:e.detail.encryptedData,
              iv: e.detail.iv,
            },
            success: function(res) {
              var tmpsig = res.data;
              console.log("the return of getUserSigByTelephone is:" + tmpsig);
              console.log(res);
              console.log(tmpsig)
              if(tmpsig.success){
    
              wx.showToast({
                title: tmpsig.msg,
                duration: 2000
               });

              wx.setStorageSync('isRegistered', tmpsig.body.mobile);
             
              that.setData({
                getUser:false,
                getPhoneNumbers:true,
                btnValue:"已经登录，不需要重复登录"
              })
    
                wx.switchTab({
                  url: '../index/index',
                  success: function (e) {
                    let page = getCurrentPages().pop();
                    if (page == undefined || page == null) return;
                    page.onLoad();
                }
              })

              }
    
              if(!tmpsig.success){

                if(tmpsig.errorCode==401){
                  wx.showToast({
                    title: '请登录',
                    duration: 2000
                  });
                  that.setData({
                    getUser:true,
                    getPhoneNumbers:false
                  })

                }else{
                  wx.showToast({
                    title: '获取失败,请重试',
                    duration: 2000
                  });
                  that.setData({
                    getPhoneNumbers:true,
                    getUser:false,
                  })
                }
              }
            },

            fail: function(resp) {

              wx.showToast({
                title: '请联系管理人员',
                duration: 2000
              });

              console.log("getUserSigByTelephone failed,the response is %o", resp)
              return false;
            },
            complete: function(res) {
              // console.log("the return of consultantRegister complete is:" + res.data);
              // console.log(res);
            } //请求完成后执行的函数
          })

        }else {
          // wx.reLaunch({
          //     url: '../index/index'
          //   })
          wx.showToast({
            title: '请登录',
            duration: 1000
          });

          that.setData({
            getUser:false,
            getPhoneNumbers:false
          })

        }
      },

      fail:function(res){
        console.log(res,'')
          wx.showToast({
            title: '登录过期了',
            duration: 1000
          });

        
      }
    })
  },




  //click the button to login
  login: function(e) {
    var that = this;
     
    //get the telephone from the 
    console.log("get the userSig by telephone", that.data.username);
    // get the userSig
    getUserSigByTelephone(that.data.username);
  },

  // this function will show the msg to custom
  

  onShow: function(e) {
    var that = this;
    
    // 获取本地存储的用户电话号码，如果获取成功，就弹出提示“已经登录，不需要重复登录”
    var isRegistered = wx.getStorageSync('isRegistered');


    // if (isRegistered) {
      
    //   this.setData({
    //     // loginBtnShow: false,
    //     // getPhoneNumbers:false,
    //     telephone:isRegistered
    //   });
  //   }else{
  //   }

  // let token1=wx.getStorageSync('token')


  //   that.setData({
  //     token:token1
  //   })

  //   wx.request({
  //     // url: "https://www.cdlpkj.cn/school/a/iim/im/Landing",
  //     url: util.api+"/iim/im/Landing",
  //     data: {
  //       token:token1,
  //       },
  //       success: function(res) {
  //         var tmpsig = res.data;
  //         console.log("the return of getUserSigByTelephone is:" + tmpsig);
  //         console.log(res)

  //         if(!tmpsig.success){    
  //           that.setData({
  //             // loginBtnShow: true,
  //             btnValue: "登录"
  //           });
  //         }else{
  //           that.setData({
  //             getPhoneNumbers:false,
  //             btnValue:"已经登录，不需要重复登录"
  //           })       
  //         }


  //       },
  //       fail: function(resp) {
  //         console.log("getUserSigByTelephone failed,the response is %o", resp)
  //         return false;
  //       },
  //       complete: function(res) {
  //         // console.log("the return of consultantRegister complete is:" + res.data);
  //         // console.log(res);
  //       } //请求完成后执行的函数
  //     })




  },
  //end onShow

  //call some test function
  test: function() {

  },

     //授权

  loginGin: function(e) {
      console.log('登录')
      let that = this;
      wx.login({
        success: function(res) {
          console.log(res)
          if (res.code) {
            console.log(e)
            that.goLogin(res.code, e.detail.encryptedData, e.detail.iv);
          } else {
            wx.showModal({
              title: '提示',
              content: '获取用户信息超时，请重试',
              showCancel: false,
              success: function (res) {
                  that.setData({
                    getUser:true
                  })
              }
            })
          }
        }
      });
    },
  
    goLogin(code,encryptedData,iv){

      let that=this

      wx.request({
  
        // url: "https://www.cdlpkj.cn/school/a/iim/im/onLogin",
        url: util.api+"/iim/im/onLogin",
        data: {
          code:code,
          encryptedData:encryptedData,
          iv:iv
        },
        success: function(res) {
          var tmpsig = res.data;
          console.log("the return of getUserSigByTelephone is:" + tmpsig);
          console.log(res);
          console.log(tmpsig)
          app.isPhoneNumber();//判断是否随机生成手机号
          if(tmpsig.success){

            wx.showToast({
              title: tmpsig.msg,
              duration: 2000
            });
          wx.setStorageSync('userId', tmpsig.body.data.id);    // 用户ID
          wx.setStorageSync('token', tmpsig.body.token);
          // wx.setStorageSync('isRegistered', tmpsig.body.data.mobile);
          wx.setStorageSync('loginName', tmpsig.body.data.loginName);
          wx.setStorageSync('userType', tmpsig.body.data.userType);

          that.setData({
            getUser:false,
            getPhoneNumbers:true
          })

          //   wx.switchTab({
          //     url: '../index/index',
          //     success: function (e) {
          //       let page = getCurrentPages().pop();
          //       if (page == undefined || page == null) return;
          //       page.onLoad();
          //   }
          // })
          }

          if(!tmpsig.success){
            wx.showToast({
              title: '登录失败',
              duration: 2000
            });

            that.setData({
              getUser:true,
            })
          }
          
        

        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        },
        complete: function(res) {
          // console.log("the return of consultantRegister complete is:" + res.data);
          // console.log(res);
        } //请求完成后执行的函数
      })
    },
  

    bindKeyInput: function (e) {
      this.setData({
        phoneNumber: e.detail.value
      })
    },

    bindCodeInput: function (e) {
      this.setData({
        code: e.detail.value
      })
    },

    information: function(){
      
      this.setData({
        information:true
      })
    },

    
    sendNote: function(){
      let that=this
      console.log(that.data.phoneNumber )
      
      if(that.data.phoneNumber==''){
        wx.showToast({title: '请输入手机号',duration: 2000});
        return
      }
      if(that.data.phoneNumber.length<11){
        wx.showToast({title: '请输入正确的手机号',duration: 2000});
        return
      }

      wx.request({
        url: util.api+"/iim/im/sendNote",
        data: {
          mobile:that.data.phoneNumber,
        },

        success: function(res) {

          var tmpsig = res.data;

          console.log("the return of getUserSigByTelephone is:" + tmpsig);
        

          console.log(tmpsig)

          if(tmpsig.success){
          
          }

          if(!tmpsig.success){
            wx.showToast({
              title: tmpsig.msg,
              duration: 2000
            });
         
          }

        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        }
      })
    },
 
//example.js
submit: function (e) {

  console.log(e)

  console.log(e.detail.formId);
},
    

    editPhone: function(){
      let that=this
      console.log(that.data.phoneNumber )
      console.log(that.data.phCode )

      if(that.data.phoneNumber==''){
        wx.showToast({title: '请输入手机号',duration: 2000});
        return
      }

      if(that.data.phCode==''){
        wx.showToast({title: '请输入验证码',duration: 2000});
        return
      }

      wx.request({
        url: util.api+"/iim/im/editPhone",
        data: {
          token:wx.getStorageSync('token'),
          phone:that.data.phoneNumber,
          code:that.data.phCode,
        },

        success: function(res) {
          var tmpsig = res.data;

          console.log("the return of getUserSigByTelephone is:" + tmpsig);
        

          console.log(tmpsig)

          if(tmpsig.success){
          
          }

          if(!tmpsig.success){
            wx.showToast({
              title: tmpsig.msg,
              duration: 2000
            });
         
          }

        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        }
      })
    }
  
  


})
//end Page



//user defined function
function getUserSigByTelephone(telephone) {
  wx.request({
    url: "https://www.xuezhou.xyz/getUserSigByTelephone",
    data: {
      "telephone": telephone
    },
    success: function(res) {
      var tmpsig = res.data;
      console.log("the return of getUserSigByTelephone is:" + tmpsig);
      console.log(res);
      app.globalData.identifier = telephone;
      app.globalData.userSig = tmpsig;
      console.log("the userSig get from server is %o", app.globalData.userSig);
      //store telephone UserSig To Local Storage
      imutil.storetelephoneUserSigToLocalStorage(telephone, tmpsig);
      var len = tmpsig.length
      // getUserSigByTelephone successfully
      if (len > 0) {
        wx.showToast({
          title: '登录成功',
          duration: 2000
        });

        //暂停（setTimeout）2秒，让showToast可以执行完毕
        setTimeout(function() {
          console.log("now we go to home page");
          // 跳转至历史咨询
          wx.switchTab({
            url: '../index/index'
          })
          // 结束跳转
        }, 2000);
      } else {
        wx.showToast({
          title: '登录失败',
          duration: 2000
        });
      }

    },
    fail: function(resp) {
      console.log("getUserSigByTelephone failed,the response is %o", resp)
      return false;
    },
    complete: function(res) {
      // console.log("the return of consultantRegister complete is:" + res.data);
      // console.log(res);
    } //请求完成后执行的函数
  })
  // end wx.request
}
// end getUserSigByTelephone

//user defined function
// 同意授权的情况下，解密数据，获取电话号码
function decryptPhoneNumber(encryptedData, iv) {
  var appId = app.globalData.appid;
  console.log("app.globalData.appid is %o", app.globalData.appid)
  var sessionKey = app.globalData.session_key;
  var pc = new WXBizDataCrypt(appId, sessionKey)

  var data = pc.decryptData(encryptedData, iv)
  if (data) {
    console.log('解密后 data: ', data);
    return data.phoneNumber;
  } else {
    console.log("the data is cleared,please reopen the mini prigram");
    wx.showModal({
      title: '获取手机号失败，请完全退出并重新进入小程序',
      icon: 'fail',
      duration: 3000
    });

    //暂停（setTimeout）2秒，让showToast可以执行完毕
    setTimeout(function () {
      console.log("must logout")
      return false;
    }, 3000)
  }

}
//end decryptPhoneNumber


